package com.eastidea.live.hibernet;

import java.sql.Types;
import java.util.Properties;

import org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.ReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.TableIdentifier;

/**
 * This class customizes the implementation of
 * DelegatingReverseEngineeringStrategy. It controls the way of the primary keys
 * are generated. The method getTableIdentifierStrategyName specifies the
 * choosen strategy for pk generation - in this case Oracle sequences are being
 * used. The method getTableIdentifierProperties alters the way the sequence
 * name is created.
 * 
 * @author Nikolai Gagov
 * 
 */
public class CustomReverseEngineeringStrategy extends
		DelegatingReverseEngineeringStrategy {

	/**
	 * @param delegate
	 */
	public CustomReverseEngineeringStrategy(ReverseEngineeringStrategy delegate) {

		super(delegate);
	}

	@Override
	public String getTableIdentifierStrategyName(TableIdentifier tableIdentifier) {

		return "sequence";
	}

	@Override
	public Properties getTableIdentifierProperties(
			TableIdentifier tableIdentifier) {

		final String name = tableIdentifier.getName();

		Properties p = super.getTableIdentifierProperties(tableIdentifier);

		if (p == null) {
			p = new Properties();
		}

		if (name != null) {

			p.put("sequence", name.toLowerCase() + "_seq");
			p.put("generatorName", name.toLowerCase() + "_seq_gen");
		}

		return p;
	}

	@Override
	public String columnToHibernateTypeName(TableIdentifier table,
			String columnName, int sqlType, int length, int precision,
			int scale, boolean nullable, boolean generatedIdentifier) {
		String result = null;

		switch (sqlType) {
		case Types.DATE:
		case Types.TIME:
		case Types.TIMESTAMP: {
			result = "timestamp";
			break;
		}

		default: {
			result = super.columnToHibernateTypeName(table, columnName,
					sqlType, length, precision, scale, nullable,
					generatedIdentifier);
			break;
		}
		}
		if (table.getName().toLowerCase().indexOf("uvst") >= 0) {
			System.out.println("columnToHibernateTypeName = " + result
					+ ", table = " + table + ", columnName = " + columnName
					+ ", sqlType = " + sqlType + ", length = " + length
					+ ", precision = " + precision + ", scale = " + scale
					+ ", nullable = " + nullable + ", generatedIdentifier = "
					+ generatedIdentifier);
		}
		return result;
	}

	@Override
	public String tableToCompositeIdName(TableIdentifier table) {
		String result = super.tableToCompositeIdName(table);
		if (table.getName().toLowerCase().indexOf("uvst") >= 0) {
			System.out.println("tableToCompositeIdName = " + result
					+ ", table = " + table);
		}
		return result;
	}

	@Override
	public String classNameToCompositeIdName(String arg0) {
		return super.classNameToCompositeIdName(arg0);
	}
}
